import {Component, OnDestroy, OnInit} from "@angular/core";
import {sjgzxinModuledatas} from "../pubcomponent/pageTitle.datas";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";

declare var $: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
        <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
        </div>
      <div class="portlet-body">
        <div class="row">
          <form class="form-horizontal">
            <div class="col-lg-8">
              <fieldset>
                <legend>报警参数设置</legend>
                <ng-container *ngIf="bjcssz.length">
                  <div class="form-group" *ngFor="let obj of bjcssz">
                    <label class="col-lg-4 control-label" [for]="obj.key">
                      <require-label></require-label>
                      {{obj.name}}</label>
                    <div class="col-lg-5">
                      <input type="text" name="bjcspzxm" class="form-control input-inline input-medium" [id]="obj.key"
                             [value]="obj.value"/>
                      <span class="help-inline"> ({{obj.dw}})</span>
                      <div *ngIf="obj.warn">
                        <tool-tip [o]="obj.warntext"></tool-tip>
                      </div>
                    </div>
                  </div>
                </ng-container>
              </fieldset>
            </div>
          </form>
        </div>
        <div class="row">
          <form class="form-horizontal">
            <div class="col-lg-12">
              <fieldset>
                <legend>报警推送设置</legend>
                <ng-container *ngIf="bjtspz.length">
                  <div class="row">
                    <div class="col-lg-3" *ngFor="let group of bjtspz">
                      <div class="grouptitle">{{group.groupmc}}</div>
                      <div class="form-group" *ngFor="let obj of group.children">
                        <label class="control-label col-lg-6">{{obj.name}}</label>
                        <div class="col-lg-6">
                        <span class="form-control icon_on" *ngIf="obj.checked"
                              (click)="toggleOnOff(obj)">
                          <i class="fa fa-toggle-on"></i>
                        </span>
                          <span class="form-control icon_off"
                                *ngIf="!obj.checked" (click)="toggleOnOff(obj)">
                            <i class="fa fa-toggle-off"></i>
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </ng-container>
              </fieldset>
            </div>
          </form>
        </div>
      </div>
    </div>
  `,
  styles: [
    ".grouptitle{height: 50px;text-align: center;background-color: beige;line-height: 50px;font-size: 15px;font-weight: bold; color: blue;}",
    ".icon_on{color: blue;border: none;cursor: pointer;font-size: 20px}",
    ".icon_off{color: #000;border: none;cursor: pointer;font-size: 20px}"
  ]
})
export class TjbbGjszComponent implements OnInit, OnDestroy {
  actionobj1: any[] = [{
    pfrom: "gjpz",
    title: "保存",
    type: "save",
    show: true
  }];
  // 报警类型参数设置
  bjcsKeyValue: any = {
    bjsjjg: "报警时间间隔",
    bmsfw: "保密室范围",
    csyz: "超速阈值",
    cstlyz: "超时停留阈值",
    dzbqlxjg: "电子标签离线间隔",
    sczdlxjg: "手持终端离线间隔"
  };
  // 报警类型参数单位
  bjcsdwKeyValue: any = {
    bjsjjg: "分钟",
    bmsfw: "米",
    csyz: "Km/h",
    cstlyz: "分钟",
    dzbqlxjg: "分钟",
    sczdlxjg: "分钟"
  }


  // 推送报警中的分组
  bjtsGroup: any = {
    "07": "试卷出库异常",
    "08": "试卷入库异常",
    "11": "低电量告警"
  }
  //推送报警
  bjtsKeyValue: any = {
    "01": "试卷多拉",
    "02": "试卷少拉",
    "03": "试卷错拉",
    "04": "超时停留",
    "05": "超出围栏",
    "06": "超速告警",
    "0701": "试卷出库异常-考点",
    "0702": "试卷出库异常-保密室",
    "0801": "试卷入库异常-保密室",
    "0802": "试卷入库异常-考点",
    "0803": "试卷入库异常-评卷中心",
    "09": "试卷位置异常",
    "10": "离线告警",
    "1101": "手持终端电量低",
    "1102": "标签GNSS电量低",
    "1103": "标签蓝牙电量低",
    "12": "故障告警"
  };

  bjcssz: any[] = [];  // 数据驱动 UI,  取值
  bjtspz: any[] = []; // 数据驱动 UI,  取值


  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "gjpz") {
      if (actiontype === "save") {
        this.savePz();
      }
    }
  }

  /**
   * 获取配置信息
   */
  getpzxx(): void {
    const url = "sjgz/zsymtjbb/cxbjxxtspz";
    this.itservice.kwPtPost(url, null).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const bjyzpzListv = resp.bjyzpzList ? resp.bjyzpzList : [];  // 报警参数配置
            const bjtspzListv = resp.bjtspzList ? resp.bjtspzList : []; // 推送报警项

            if (!bjyzpzListv.length) {
              this.bjcssz.length = 0;
              return
            }
            this.bjcssz = bjyzpzListv.map((obj) => {
              const bjyzlxv = obj.bjyzlx;// 设置参数类型
              const yzv = obj.yz; // 设置参数值
              return {
                name: this.bjcsKeyValue[bjyzlxv],
                key: bjyzlxv,
                value: yzv,
                dw: this.bjcsdwKeyValue[bjyzlxv],
                warn: false,
                warntext: ""
              }
            });
            if (!bjtspzListv.length) {
              this.bjtspz.length = 0;
              return
            }
            const groupkeyChildren: any = {};  //key -groupkey  value ---chidlren
            const basegroupChildren: any[] = [];  //其他的都归一堆
            this.bjtspz.push({
              groupmc: "",
              groupkey: "base",
              children: []
            });


            bjtspzListv.forEach((obj) => {
              const bjlxmv = obj.bjlxm; // 报警类型码
              const sftsv = obj.sfts; // 是否推送：0 推送；1 不推送
              const bjlxmstr = bjlxmv.toString().trim();
              const bjlxmLen = bjlxmstr.length;  // 类型码长度大于2 ， 就是有组出现

              if (bjlxmLen > 2) {
                const group_key = bjlxmstr.substring(0, 2);
                if (!groupkeyChildren[group_key]) {
                  groupkeyChildren[group_key] = [{
                    name: this.bjtsKeyValue[bjlxmv],
                    key: bjlxmv,
                    checked: (sftsv === '0') ? true : false,
                  }];
                  this.bjtspz.push({
                    groupmc: this.bjtsGroup[group_key],
                    groupkey: group_key,
                    children: []
                  })
                } else {
                  groupkeyChildren[group_key].push({
                    name: this.bjtsKeyValue[bjlxmv],
                    key: bjlxmv,
                    checked: (sftsv === '0') ? true : false,
                  })
                }
              } else {
                // this.bjtspz.push({
                //   groupmc: "",
                //   groupkey: "",
                //   children: [{
                //     name: this.bjtsKeyValue[bjlxmv],
                //     key: bjlxmv,
                //     checked: (sftsv === '0') ? true : false,
                //   }]
                // })
                basegroupChildren.push({
                  name: this.bjtsKeyValue[bjlxmv],
                  key: bjlxmv,
                  checked: (sftsv === '0') ? true : false,
                });
              }
            });
            this.bjtspz[0].children = basegroupChildren;
            this.bjtspz.forEach((obj) => {
              const groupkey = obj.groupkey;
              if (groupkey != 'base') {
                obj.children = groupkeyChildren[groupkey];
              }
            });
            console.log("推送报警配置", this.bjtspz.sort());
          }
        }
      });
    })
  }

  toggleOnOff(pzobj: any): void {
    pzobj.checked = !pzobj.checked;
  }

  /**
   * 保存
   */
  savePz(): void {
    this.commservice.log("bjcs", this.bjcssz);
    this.commservice.log("bjts", this.bjtspz);
    const bjyzpzList: any[] = [];// 参数配置
    const bjtspzList: any[] = []; // 推送
    let bjcsformvaild: number = 1;
    this.bjcssz.forEach((obj, index) => {
      const itv = $("input[name='bjcspzxm']").eq(index).val();
      bjyzpzList.push({
        bjyzlx: obj.key,
        yz: itv
      });
      const regex = /^[1-9]\d*$/;
      if (!regex.test(itv)) {
        obj.warn = true;
        obj.warntext = "仅支持正整数";
        bjcsformvaild *= 0;
      } else {
        obj.warn = false;
        obj.warntext = "";
        bjcsformvaild *= 1;
      }
    });
    if (!bjcsformvaild) {
      return
    }
    this.bjtspz.forEach((group) => {
      const children = group.children;
      children.forEach((obj) => {
        bjtspzList.push({
          bjlxm: obj.key,
          sfts: obj.checked ? "0" : "1"
        });
      });
    });
    this.commservice.log("save_bjcs", bjyzpzList);
    this.commservice.log("save_bjts", bjtspzList);
    this.commservice.blockUI({
      boxed: true,
      message: "保存中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    const url = "sjgz/zsymtjbb/bjxxtspz";
    this.itservice.kwPtPost(url, {
      bjyzpzList: bjyzpzList,
      bjtspzList: bjtspzList
    }).subscribe(resp => {
      this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            this.commservice.myswal("success", resp, "", "ts", null);
          }
        }
      });
    });

  }

  constructor(private commservice: CommService,
              private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.getpzxx();
  }

  ngOnDestroy() {

  }

}
